package com.ihealthway.all.interfaces.dwihealth.ws;

import com.ihealthway.all.commons.Constants;
import com.ihealthway.all.interfaces.dwihealth.XMLBuilder;
import com.ihealthway.all.interfaces.dwihealth.service.DWCustomerService;
import com.ihealthway.all.interfaces.dwihealth.service.DWServicePlanService;
import com.ihealthway.all.interfaces.dwihealth.vo.*;
import com.ihealthway.all.utils.JaxbUtil;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import javax.jws.WebService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 东吴接口实现
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean
@WebService(endpointInterface="com.ihealthway.all.interfaces.dwihealth.ws.IDWSyncBaseData", serviceName = "DWSyncBaseData")
public class DWSyncBaseData implements IDWSyncBaseData {

    private static final Log logger = Logs.get();

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

    @Inject
    private PropertiesProxy conf;
    @Inject
    private DWCustomerService custService;
    @Inject
    private DWServicePlanService serverPlanService;

    @Override
    public String syncCustomerInfo(String reqContent) {

        String respContent = doSync(reqContent, 1);

        return respContent;
    }

    @Override
    public String syncServicePlan(String reqContent) {

        String respContent = doSync(reqContent, 2);

        return respContent;
    }

    /**
     * 执行同步数据操作
     * @param reqContent    同步XML内容
     * @param mode  1 客户信息 2 服务信息
     * @return 操作返回内容
     */
    private String doSync(String reqContent, int mode) {

        ValidTuple vt =  prepareSync(reqContent);
        String respContent = vt.message;

        InterProtocolReq ipc = vt.reqContent;
        if (ipc == null) {
            return respContent;
        }

        respContent = XMLBuilder.simpleResp("0", "未发现同步的客户信息数据");

        List<DWCustomer> customers = ipc.getBody().getCustomers();
        List<DWServicePlan> servicePlans = ipc.getBody().getServicePlans();
        if ((customers!=null && !customers.isEmpty())
                || (servicePlans!=null && !servicePlans.isEmpty())) {
            switch (ipc.getHead().getDataType()) {
                case Constants.DW_SYNC_ADD_DATA_TYPE:
                    respContent = mode==1 ? custService.syncAdd(customers)
                            : serverPlanService.syncAdd(servicePlans);
                    break;
                case Constants.DW_SYNC_UPDATE_DATA_TYPE:
                    respContent = mode==1 ? custService.syncUpdate(customers)
                            : serverPlanService.syncUpdate(servicePlans);
                    break;
                default:
                    respContent = XMLBuilder.simpleResp("0",
                            "发现不支持的DataType: "+ipc.getHead().getDataType());
                    break;
            }
        }

        return respContent;
    }


    /**
     *  准备同步数据处理
     * @param reqContent 同步XML内容
     * @return  校验多元数据
     */
    private ValidTuple prepareSync(String reqContent) {

        InterProtocolReq reqCnt = null;
        String respContent = null;

        if (!Strings.startsWithChar(reqContent, '<')
                || !Strings.endsWithChar(reqContent, '>')) {
            respContent = XMLBuilder.simpleResp("0", "请求数据为空或格式不对");
            return new ValidTuple(reqCnt, respContent);
        }

        try {
            reqCnt = JaxbUtil.toBean(reqContent, InterProtocolReq.class, "TXLifeRequest");
        } catch (Exception e) {
            logger.errorf("%s", reqContent);
            logger.error("Parser DW interface xml request failed!!!", e);
            respContent = XMLBuilder.simpleResp("0", "请求数据语法格式有误");
            return new ValidTuple(reqCnt, respContent);
        }

        logger.infof("reqContent: %s", reqContent);

        if (reqCnt != null
                && reqCnt.getHead() != null
                && !checkAccessKey(reqCnt.getHead().getAccessKey())) {
            respContent = XMLBuilder.simpleResp("0", "密钥验证错误未能授权");
            reqCnt = null;
        }

        return new ValidTuple(reqCnt, respContent);
    }

    /**
     * 指定字符串的32位MD5加密字符串
     * @param ak    交互密钥
     * @return  true或者false
     */
    private boolean checkAccessKey(String ak) {

        if (Strings.isNotBlank(ak) && Lang.length(ak)==32) {
            String date = DATE_FORMAT.format(new Date());
            String tmp = Lang.md5(conf.get("dw_ws_ak")+date);

            boolean flag = Strings.equalsIgnoreCase(ak, tmp);
            if (!flag) {
                logger.errorf("AccessKey failed. [ak: %s, tmp: %s, date: %s, dw_ak: %s]",
                        ak, tmp, date, conf.get("dw_ws_ak"));
            }
            return flag;
        }

        return false;
    }

}
